<?php

namespace app\mbti\controller;
use think\Db;
use app\common\controller\Mbti;
class Index extends Mbti
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * MbtiScene场景模型对象
     * @var \app\mbti\model\MbtiScene
     */
    protected $sceneModel = null;
    /**
     * MbtiResult场景结果模型对象
     * @var \app\mbti\model\MbtiResult
     */
    protected $resultModel = null;
    /**
     * MbtiEvaluate测评结果模型对象
     * @var \app\mbti\model\MbtiEvaluate
     */
    protected $evaluateModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->sceneModel = new \app\mbti\model\MbtiScene;
        $this->resultModel = new \app\mbti\model\MbtiResult;
        $this->evaluateModel = new \app\mbti\model\MbtiEvaluate;
        $this->assignconfig('wx_config', 123456);
    }

    public function index()
    {
        if($this->wxConfig){
            $this->assignconfig('wx_config', $this->wxConfig);
        }
        return $this->view->fetch();
    }

    public function detail()
    {
        $sceneId = $this->request->param('scene_id', 0, 'intval');
        $scene = $this->sceneModel->where(["id" => $sceneId, "status" => "normal"])->find();
        if(!$scene){
            $this->error("场景不存在或已被禁用");
        }
        config('url_common_param', true);
        $url = url('mbti/index/detail', ['scene_id' => $sceneId], true, true);
        if (!$this->auth->isLogin()) {
            $config = get_addon_config('third');
            if (!$config['status']) {
                $this->redirect(url('mbti/user/login', ['url'=>$url], true, true));
            }else{
                $statusArr = explode(',', $config['status']);
                if(in_array('wechat', $statusArr)){
                    if(\addons\third\library\Service::isWechat()){
                        $this->redirect(url('third/connect/wechat', ['url'=>$url], true, true));
                    }else{
                        $this->redirect(url('mbti/user/login', ['url'=>$url], true, true));
                    }
                }
            }
        }
        $userInfo = $this->auth->getUser();
        if($this->wxConfig){
            $this->assignconfig('wx_config', $this->wxConfig);
        }
        $wxSite = [
            "title" => $scene['share_title'],
            "desc" => $scene['share_desc'],
            "link" => $url,
            "imgUrl" => cdnurl($scene['share_logo'], $this->request->domain())
        ];
        $this->assignconfig('wx_share', $wxSite);
        $evaluateInfo = $this->evaluateModel->where(['scene_id' => $scene["id"], 'user_id' => $userInfo["id"]])->field("id,answers")->find();
        $this->assign("evaluate_id", $evaluateInfo ? $evaluateInfo['id'] : 0);
        $this->assign("usrInfo", $userInfo);
        $this->assign("scene", $scene);
        $this->assign("title", $scene["name"]);
        $this->assignconfig("evaluateId", $evaluateInfo ? $evaluateInfo['id'] : 0);
        $this->assignconfig("sceneId", $scene['id']);
        $this->assignconfig("applet_path", config("site.applet_path"));
        return $this->view->fetch();
    }

    public function sms_tool(){
        try {
            $smsConfig = get_addon_config('alisms');
            $page = intval($this->request->request('page', 1, 'intval'));
            $perPage = intval($this->request->request('page_size', 10, 'intval'));
            $count = Db::name('mbti_sms')->count();
            $phones = Db::name('mbti_sms')->where(['id'=>["BETWEEN", [(($page-1)*$perPage+1), $page*$perPage]], 'is_send' => 0])->order(['id' => 'ASC'])->field(['id', 'name', 'service_provider', 'mobile'])->select();
            $this->assign("title", "短信测试工具");
            $this->assignconfig("sms_page", $page);
            $this->assignconfig("sms_max_page", $count % $perPage == 0 ? ($count ? intval($count/$perPage) : 1) : ceil($count/$perPage));
            $this->assignconfig("phones", count($phones) > 0 ? $phones : []);
            if($this->wxConfig){
                $this->assignconfig('wx_config', $this->wxConfig);
            }
            return $this->view->fetch();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    //发送测试短信
    public function sms_send()
    {
        $mobile = $this->request->post('mobile');//必须
        $template = $this->request->post('template');//必须
        $id = $this->request->post('id', 0, "intval");//必须
        $sign = $this->request->post('sign', '');//无值使用配置值
        $postParam = $this->request->post('param', '', 'trim');//无值则生成验证码
        try{
            config("default_return_type", "json");
            $config = get_addon_config('alisms');
            if (!$mobile) {
                throw new \Exception('手机号不能为空');
            }
            $templateArr = $config['template'] ?? [];
            if (!isset($templateArr[$template]) || !$templateArr[$template]) {
                throw new \Exception('后台未配置对应的模板CODE');
            }
            $template = $templateArr[$template];
            $sign = $sign ?: $config['sign'];
            $param = $postParam ? (array)json_decode($postParam) : ['code' => mt_rand(100000, 999999)];
            $alisms = new \addons\alisms\library\Alisms();
            $ret = $alisms->mobile($mobile)
                ->template($template)
                ->sign($sign)
                ->param($param)
                ->send();
            if ($ret) {
                Db::name('mbti_sms')->where(['id'=>$id])->update(["is_send"=>1,"result"=>"发送成功"]);
                return ["code"=>"1","msg"=>"发送成功", "data"=>"发送成功"];
            } else {
                throw new \Exception($alisms->getError());
            }
        }catch (\Exception $e){
            Db::name('mbti_sms')->where(['id'=>$id])->update(["is_send"=>0,"result"=>$alisms->getError()]);
            return ["code"=>"0","msg"=>$e->getMessage(), "data"=>"发送失败"];
        }
    }
}
